package com.um.jdy.mp.device.event;


import cn.hutool.json.JSONUtil;
import com.um.jdy.common.device.entity.po.Fee;
import com.um.jdy.common.device.entity.po.Pile;
import com.um.jdy.common.device.enums.DeviceEnum;
import com.um.jdy.common.device.events.FeeEvent;
import com.um.jdy.common.device.service.PileService;
import com.um.jdy.rpc.enums.DeviceTypeEnum;
import com.um.jdy.rpc.ev.confirmation.SetPriceModelConfirmation;
import com.um.jdy.rpc.ev.enums.ConfirmationStatus;
import com.um.jdy.rpc.factory.ServiceFactory;
import com.um.springboot.starter.utils.StringUtil;
import com.um.springcloud.dubbo.cluster.DeviceKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 事件处理监听器
 *
 * @author 甘天伟
 * @date 2022/1/28
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Component
public class FeeEventListener {

    @Autowired
    ServiceFactory serviceFactory;

    @Autowired
    PileService pileService;
    
    @Async
    @EventListener
    public void handleUpdateFeeEvent(FeeEvent<Fee> event) {
        try {
            log.info("handle Update Fee event {} data {}", event.getData().getClass().getSimpleName(),
                    JSONUtil.toJsonStr(event.getData()));

            List<Pile> pileList = pileService.getRows("device_fee_id",event.getData().getDeviceFeeId());
            for(Pile pile : pileList){
                try {
                    if (DeviceTypeEnum.EV.name().equals(pile.getDeviceType()) && StringUtil.equals(pile.getDeviceStatus(), DeviceEnum.DeviceStatus.Online.name())) {
                        SetPriceModelConfirmation confirmation = serviceFactory.getRpcEVDeviceService(pile.getProtocol()).setPriceModel(new DeviceKey(pile.getImei()));

                        if (confirmation.getStatus() == ConfirmationStatus.Accepted) {
                            log.info("更价成功：{}", confirmation.getReason());
                        } else {
                            log.info("更价失败：{}", confirmation.getReason());
                        }
                    }
                }catch (Exception ex){
                    log.error("更价出错：{}",ex.getMessage());
                }
            }
        } catch (Exception e) {
            //TODO:重试机制处理
            log.error("handle event error ", e);
        }
    }
}
